<template>
	<view :style="[AppSkinVar]" class="setting-wrapper">
		<view class="bg-white e-p-l-30 e-p-r-30">
			<view class="item-box h-124 e-flex">
				<text class="e-font-30">
					{{ toI18('头像') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end">
					<e-avatar :defaultUrl="$staticPath('default-headerImg.png')" :src="$fullLink(userInfo.photo)"
						size="100rpx" @click="changeAvatar"></e-avatar>
				</view>
				<view class="e-m-l-10 e-p-t-10">
					<image class="img-36" src="../static/setting/arrow_right.png"></image>
				</view>
			</view>
			<view class="item-box h-100 e-flex">
				<text class="e-font-30">
					{{ toI18('昵称') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end" @tap="handleToEdit(3)">
					<text class="e-font-30 f-80">{{ userInfo.nickname || '' }}</text>
					<view class="e-m-l-10 e-p-t-10">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
			<view class="item-box h-100 e-flex" v-if="registerType[0]">
				<text class="e-font-30">
					{{ userI18('手机号') }}
				</text>
				<!--  @tap="handleToEdit(2)" 暂时不给编辑手机号  -->
				<view class="e-flex-1 e-flex e-flex-end" @tap="handleToEdit(2)">
					<text class="e-font-30 f-80">{{ userInfo.phone || '' }}</text>
					<view class="e-m-l-10 e-p-t-10">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
			<view class="item-box h-100 e-flex" v-if="registerType[1]">
				<text class="e-font-30">
					{{ toI18('邮箱') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end" @tap="handleToEdit(1)">
					<text class="e-font-30 f-80">{{ userInfo.email || '' }}</text>
					<view class="e-m-l-10 e-p-t-10" v-if="!userInfo.email">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
			<view class="item-box h-100 e-flex">
				<text class="e-font-30">
					推广人
				</text>
				<view class="e-flex-1 e-flex e-flex-end" @tap="jumpBindRecommender">
					<text class="e-font-30 f-80">{{ userInfo.parentPhone }}</text>
					<view class="e-m-l-10 e-p-t-10">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
			<view class="item-box h-100 e-flex" v-if="userInfo.salt">
				<text class="e-font-30">
					{{ userI18('邀请码') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end">
					<text class="e-font-30 f-80">{{ userInfo.salt }}</text>
				</view>
			</view>

			<view class="item-box h-100 e-flex">
				<text class="e-font-30">
					{{ toI18('性别') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end" @tap="showSexPicker = true">
					<text
						class="e-font-30 f-80">{{ userInfo.userSex ? toI18(getUserSex(Number(userInfo.userSex))):'' }}</text>
					<view class="e-m-l-10 e-p-t-10">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
			<view class="item-box h-100 e-flex">
				<text class="e-font-30">
					{{ toI18('生日') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end" @tap="showBirthday = true">
					<text class="e-font-30 f-80">{{ userInfo.userBirthday }}</text>
					<view class="e-m-l-10 e-p-t-10">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="bg-white e-p-l-30 e-p-r-30 e-m-t-20">
			<view class="h-100 e-flex">
				<text class="e-font-30">
					{{ toI18('修改登录密码') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end" @tap="editLoginPwd">
					<view class="e-m-l-10 e-p-t-10">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
			<view class="item-box h-100 e-flex">
				<text class="e-font-30">
					{{ toI18('修改支付密码') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end" @tap="editPayPwd">
					<view class="e-m-l-10 e-p-t-10">
						<image class="img-36" src="../static/setting/arrow_right.png"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="bg-white e-p-l-30 e-p-r-30 e-m-t-20">
			<view class="item-box h-100 e-flex">
				<text class="e-font-30">
					{{ toI18('系统语言设置') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end text-right h-100" @tap="showPicker = true">
					<text>{{ lang }}</text>
				</view>
				<view class="e-m-l-10 e-p-t-10" @tap="showPicker = true">
					<image class="img-36" src="../static/setting/arrow_right.png"></image>
				</view>
			</view>
			<view class="h-100 e-flex">
				<text class="e-font-30">
					{{ toI18('版本') }}
				</text>
				<view class="e-flex-1 e-flex e-flex-end text-right h-100" @tap="handleUpgrade">
					<!-- #ifdef APP-PLUS -->
					<view class="e-m-r-10" :class="{ 'red-dot': appVersionTips }"></view>
					<!-- #endif -->
					<text class="e-font-30 f-80">{{ version }}</text>
				</view>
				<view class="e-m-l-10 e-p-t-10" @tap="handleUpgrade">
					<image class="img-36" src="../static/setting/arrow_right.png"></image>
				</view>
			</view>
			<view class="item-box h-100 e-flex" v-if="agreeShow">
				<text class="e-font-30">
					{{ toI18('用户服务协议') }}
				</text>
				<view class="e-flex-1 text-right h-100" @tap="handleToAgree(14)"></view>
				<view class="e-m-l-10 e-p-t-10" @tap="handleToAgree(14)">
					<image class="img-36" src="../static/setting/arrow_right.png"></image>
				</view>
			</view>
			<view class="item-box h-100 e-flex" v-if="privacyShow">
				<text class="e-font-30">
					{{ toI18('隐私政策') }}
				</text>
				<view class="e-flex-1 text-right h-100" @tap="handleToAgree(15)"></view>
				<view class="e-m-l-10 e-p-t-10" @tap="handleToAgree(15)">
					<image class="img-36" src="../static/setting/arrow_right.png"></image>
				</view>
			</view>
			<view class="item-box h-100 e-flex" @tap="showPop = true">
				<text class="e-font-30">
					{{ toI18('注销账户') }}
				</text>
				<view class="e-flex-1 text-right h-100"></view>
				<view class="e-m-l-10 e-p-t-10">
					<image class="img-36" src="../static/setting/arrow_right.png"></image>
				</view>
			</view>
			<!-- #ifdef SUBSCRIPTION -->
			<view class="item-box e-flex">
				<view class="btn e-flex e-flex-xy-center e-m-t-60 e-m-b-60" @tap="handleLogout">
					<text class="e-font-30 c-white">{{ toI18('退出登录') }}</text>
				</view>
			</view>
			<!-- #endif -->
		</view>
		<!-- #ifdef APP-PLUS -->
		<upgrade ref="upgradeRef" @showAppVersionTips="appVersionTips = true"></upgrade>
		<!-- #endif -->
		<e-picker :cancelText="commonI18('取消')" :confirmText="commonI18('确认')" :show="showPicker" :columns="langList"
			@cancel="showPicker = false" @confirm="handleSetLang" keyName="countryName"></e-picker>

		<!-- 性别 -->
		<e-picker :cancelText="commonI18('取消')" :confirmText="commonI18('确认')" :show="showSexPicker"
			:columns="[[toI18('男'), toI18('女')]]" @cancel="showSexPicker = false" @confirm="handleSetSex"
			keyName="countryName"></e-picker>

		<!-- 生日 -->
		<e-datetime-picker :show="showBirthday" v-model="dateTime" mode="date" :minDate="minDate" :maxDate="maxDate"
			@confirm="handleSetBirthday" @cancel="showBirthday = false"></e-datetime-picker>


		<!-- 注销弹窗 -->
		<e-popup :show="showPop" mode="center" round="20rpx">

			<view class="collect-box border-radius-20 bg-white e-p-20">
				<view class="e-flex-xy-center e-font-30 w-600 e-m-b-60">
					{{$t('setting.确定要注销当前账号')}}
				</view>
				<view class="e-flex-xy-center e-m-b-40" @tap.stop="showAgreementPop = true">
					<view class="tips-box e-flex e-rel">
						<view class="e-abso" style="width: 100rpx;height: 40rpx;z-index: 999;">

						</view>
						<radio style="transform:scale(0.8)" :checked="isAgree" :color="AppSkin.primary"
							@tap.stop="isAgree = !isAgree" />
						<text>{{ $t('public.我已阅读并同意') }}《注销协议》</text>
					</view>
				</view>

				<view class="e-flex-xy-center">
					<view class="e-m-r-40 e-flex-xy-center cancle-btn" @tap="showPop = false">
						<text>取消</text>
					</view>
					<view class="e-flex-xy-center submit-btn"
						:style="{background:AppSkin.primary,opacity:isAgree?'1':'0.5'}" @tap="handleDel">
						<text class="c-white">确定</text>
					</view>
				</view>
			</view>
		</e-popup>
		<login-popup ref="passwordPopupRef" :show="passwordShow" @close="passwordShow = false"
			@confirm="passwordPay"></login-popup>

		<agreement-pop :showPop="showAgreementPop" @agree="isAgree = true" @cancel="isAgree = false" :isAgree="isAgree"
			agreeId="23" @close="showAgreementPop = false"></agreement-pop>
	</view>
</template>

<script lang="ts">
	import { defineComponent } from 'vue';
	// 所有可被装修选中的页面的混入，用于动态修改标题，例如装修的按钮组组件，按钮的文本为xxx，跳转到对应页面时，会将页面的标题修改为xxx
	import layoutPageTitleMixIn from '@/common/mixin/layoutPageTitleMixIn';
	export default defineComponent({
		mixins: [layoutPageTitleMixIn]
	});
</script>
<script setup lang="ts">
	import { computed, ref } from 'vue';
	import { editAvatar, editNickName, getLangList, logout, logOff } from '@/common/request/api';
	import { getLocale, setLocale } from '@/common/init/i18n';
	import { useI18n, useCurrentInstance } from '@/common/hooks';
	import { useUser, useBasics, useInit, useShoppingCart } from '@/common/stores';
	import { storeToRefs } from 'pinia';
	import { onLoad } from '@dcloudio/uni-app';
	import { rgbToHex, chooseImage } from '@/common/utils';
	import type { UpgradeInstance } from '@/typings/components'
	import loginPopup from './password.vue'
	const ctx = useCurrentInstance();
	const { setTabbarOption, setTabbarPageIndex, setTabbar, getAppConfig } = useInit();

	const toI18 = useI18n('setting');
	const publicI18 = useI18n('public');
	const userI18 = useI18n('user');
	const commonI18 = useI18n('common');
	const userStore = useUser();
	const { userInfo, isLogin } = storeToRefs(userStore);

	const jumpBindRecommender = () => {
		if (!userInfo.value.parentPhone) {
			ctx.$goTo('/pages/public/account/bindRecommender')
		}
	}

	const userBasics = useBasics();
	const { agreement, registerModel } = storeToRefs(userBasics);
	const ShoppingCartStore = useShoppingCart();
	const showPop = ref(false)
	const loading = ref(false);
	const version = ref('1.0.0');
	const appVersionTips = ref(false);
	const showPicker = ref(false);
	const langList = ref([] as any);
	const lang = ref('');
	const sexList : ['男', '女'] = ['男', '女'];
	const showSexPicker = ref(false);
	const dateTime = ref(Number(new Date()));
	const showBirthday = ref(false);
	const minDate = ref(Number(new Date('1900/01/01')));
	const maxDate = ref(Number(new Date()));
	const showAgreementPop = ref(false)
	const passwordShow = ref(false)
	const agreeShow = computed(() => {
		let data = agreement.value.find((item : any) => item.id == 14);
		return data && data.status === 1;
	});
	const privacyShow = computed(() => {
		let data = agreement.value.find((item : any) => item.id == 15);
		return data && data.status === 1;
	});
	const registerType = computed(() => {
		if (registerModel.value.length === 2) {
			return [true, true];
		} else {
			if (registerModel.value.find((item : any) => item === 'phone')) {
				return [true, false];
			} else {
				return [false, true];
			}
		}
	});

	const isAgree = ref(false)
	const handleDel = () => {
		if (!isAgree.value) return
		showPop.value = false
		isAgree.value = false
		passwordShow.value = true

	}
	const passwordPopupRef = ref();
	const passwordPay = (password : any) => {
		passwordShow.value = false
		loading.value = true
		logOff({
			password
		})
			.then((res) => {
				if (res.code === 200) {
					userStore.outLogin();
					ShoppingCartStore.removeCart();
					uni.reLaunch({
						url: '/pages/public/account/register'
					});
				} else {
					passwordPopupRef.value?.reset();
				}
			})
			.finally(() => {
				loading.value = false;
			});
	}


	const handleToAgree = (id : number) => {
		ctx.$goTo('/pages/public/txt', {
			id
		});
	};

	const editLoginPwd = () => {
		if (isLogin) {
			if (userInfo.value.phone || userInfo.value.email) {
				ctx.$goTo('/pages/public/setting/login-pwd');
			} else {
				ctx.$showModal({
					content: publicI18('绑定手机号码提示'),
					success: (res) => {
						if (res.confirm) {
							ctx.$goTo('/pages/public/account/binding');
						}
					}
				});
			}
		} else {
			ctx.$goTo('/pages/public/setting/login-pwd');
		}
	};
	const editPayPwd = () => {
		if (isLogin) {
			if (userInfo.value.phone || userInfo.value.email) {
				ctx.$goTo('/pages/public/setting/pay-pwd');
			} else {
				ctx.$showModal({
					content: publicI18('绑定手机号码提示'),
					success: (res) => {
						if (res.confirm) {
							ctx.$goTo('/pages/public/account/binding');
						}
					}
				});
			}
		} else {
			ctx.$goTo('/pages/public/setting/pay-pwd');
		}
	};

	const getUserSex = (val : number) : '男' | '女' => {
		return sexList[val];
	};

	const changeAvatar = () => {
		chooseImage({
			count: 1,
		}).then(res => {
			if (res) {
				uni.showLoading({
					title: 'loading...'
				});
				editAvatar(res.tempFiles[0].tempFilePath).then(() => {
					uni.hideLoading();
					userStore.getUserInfo();
				});
			}
		})
	};

	const handleSetSex = (val : any) => {
		showSexPicker.value = false;
		const userSex = val.indexs[0];
		editNickName({ userSex: userSex }).then((res : any) => {
			if (res.code == 200) {
				userStore.getUserInfo();
			}
		});
	};

	const handleSetBirthday = (val : any) => {
		showBirthday.value = false;
		if (val && val.value) {
			const date = new Date(val.value);
			const yyyy = date.getFullYear();
			let month : any = date.getMonth() + 1;
			let day : any = date.getDate();
			if (month < 10) month = '0' + month;
			if (day < 10) day = '0' + day;
			editNickName({ userBirthday: `${yyyy}-${month}-${day}` }).then((res : any) => {
				if (res.code == 200) {
					userStore.getUserInfo();
				}
			});
		}
	};

	const handleToEdit = (type : number) => {
		// 已绑定手机或者邮箱不可编辑（没有编辑接口只有绑定接口）
		if ((type === 1 && userInfo.value.email)) {
			return;
		}
		const content = type == 1 ? userInfo.value.email : type == 2 ? userInfo.value.phone : userInfo.value.nickname;
		ctx.$goTo('/pages/public/setting/edit', {
			type,
			content: content || ''
		});
	};
	const upgradeRef = ref<UpgradeInstance>()
	const handleUpgrade = () => {
		// #ifdef APP-PLUS
		upgradeRef.value?.checkVersion?.(true, true);
		// #endif
	};
	const handleLogout = () => {
		ctx.$showModal({
			content: toI18('确定要退出当前登录'),
			confirmText: commonI18('确定'),
			cancelText: commonI18('取消'),
			success: (res) => {
				if (res.confirm) {
					loading.value = true;
					logout()
						.then((res) => {
							setTabbarPageIndex(0);
							userStore.outLogin();
							ShoppingCartStore.removeCart();
							// #ifdef SUBSCRIPTION
							let href = location.origin + location.pathname
							window.location.href = href + '#/pages/public/account/appLogin'
							// #endif
							// #ifndef SUBSCRIPTION
							uni.reLaunch({
								url: '/pages/public/account/appLogin'
							});
							// #endif
						})
						.finally(() => {
							loading.value = false;
						});
				}
			}
		});
	};
	const handleCancellation = () => {
		ctx.$showModal({
			content: toI18('确定要注销当前账号'),
			success: (res) => {
				if (res.confirm) {
					loading.value = true;
					logOff()
						.then((res) => {
							if (res.code === 200) {
								userStore.outLogin();
								ShoppingCartStore.removeCart();
								uni.reLaunch({
									url: '/pages/public/account/register'
								});
							}
						})
						.finally(() => {
							loading.value = false;
						});
				}
			}
		});
	};

	const handleSetLang = (arr : any) => {
		const value = arr.value[0];
		lang.value = value.countryName;
		setLocale(value.countryCode);
		showPicker.value = false;
		getAppConfig().then((res) => {
			// 设置底部导航栏
			let tabbarData : any[] = [];
			// #ifdef PRIVATE
			let icon = [
				{
					text: ctx.$t('tabbar.首页'),
					pageUrl: 'home',
					icon: 'icon-shouye'
				},
				{
					text: ctx.$t('tabbar.分类'),
					pageUrl: 'classify',
					icon: 'icon-a-fenlei1'
				},
				{
					text: ctx.$t('tabbar.购物车'),
					pageUrl: 'cart',
					icon: 'icon-a-gouwuche1'
				},
				{
					text: ctx.$t('tabbar.个人中心'),
					pageUrl: 'userInfo',
					icon: 'icon-wode'
				}
			];
			icon.forEach((item, index) => {
				let data = {
					index,
					custom: false,
					link: {
						type: 2,
						pageUrl: item.pageUrl
					},
					text: item.text,
					iconPath: item.icon,
					selectedIconPath: item.icon
				};
				tabbarData.push(data);
			});
			// #endif
			// #ifndef PRIVATE
			let inactiveColor = res.bottomMenus.cssDefault ? res.bottomMenus.cssDefault.replace(/(?:\(|\)|rgba)*/g, '').split(',') : [];
			let activeColor = res.bottomMenus.cssSelect ? res.bottomMenus.cssSelect.replace(/(?:\(|\)|rgba)*/g, '').split(',') : [];
			setTabbarOption({
				inactiveColor: inactiveColor.length > 3 ? rgbToHex(`rgb(${inactiveColor[0]},${inactiveColor[1]},${inactiveColor[2]})`) : '',
				activeColor: activeColor.length > 3 ? rgbToHex(`rgb(${activeColor[0]},${activeColor[1]},${activeColor[2]})`) : '',
				bgColor: res.bottomMenus.cssBg,
				style: res.bottomMenus.cssClass
			});

			let list = JSON.parse(res.bottomMenus.layout);
			list.forEach((item : any, index : number) => {
				let data = {
					...item,
					index,
					text: item.text
				};
				if (item.custom) {
					data['iconPath'] = ctx.$fullLink(item.default_img);
					data['selectedIconPath'] = ctx.$fullLink(item.active_img);
				} else {
					data['iconPath'] = item.icon;
					data['selectedIconPath'] = item.icon;
				}
				tabbarData.push(data);
			});
			// #endif
			setTabbar(tabbarData);
			uni.$emit('appLocaleChange');
		});
	};

	onLoad(() => {
		userStore.getUserInfo();
		// #ifdef MP-WEIXIN
		let extConfig = wx.getExtConfigSync() ? wx.getExtConfigSync() : null;
		if (extConfig) {
			version.value = extConfig.version_no || '1.0.0';
		}
		// #endif
		// #ifdef APP-PLUS
		plus.runtime.getProperty(plus.runtime.appid || '', function (widgetInfo) {
			version.value = widgetInfo.version || '';
		});
		// #endif
		getLangList().then((res : any) => {
			langList.value = [res.data];
			const _l = getLocale();
			lang.value = res.data.find((item : any) => item.countryCode === _l).countryName || '';
		});
	});
</script>
<style lang="scss" scoped>
	.h-124 {
		height: 124rpx;
	}

	.h-100 {
		height: 100rpx;
	}

	.item-box {
		box-shadow: 0px -1px 0px 0px #edeff3;
	}

	.f-80 {
		color: #808080;
	}

	.btn {
		height: 100rpx;
		border-radius: 50rpx;
		background: var(--color-primary);
		width: 100%;
	}

	.h-330 {
		width: calc(100% - 48rpx);
		height: 330rpx;
		margin: 0 24rpx;
	}

	.c-4d {
		color: #4d4d4d;
	}

	.setting-wrapper {
		.red-dot {
			height: 12rpx;
			width: 12rpx;
			background: $base-color-red;
			border-radius: 50%;
		}
	}

	.collect-box {
		width: 80vw;
	}

	.cancle-btn {
		padding: 10rpx 30rpx;
		border: 1rpx solid #ccc;
		border-radius: 90rpx;
		width: 200rpx;
		height: 90rpx;
	}

	.submit-btn {
		width: 200rpx;
		height: 90rpx;
		border-radius: 90rpx;
	}
</style>